package com.programming.forum.services.impl;

import com.programming.forum.common.AppResult;
import com.programming.forum.common.ResultCode;
import com.programming.forum.dao.MessageMapper;
import com.programming.forum.exception.ApplicationException;
import com.programming.forum.model.Message;
import com.programming.forum.model.User;
import com.programming.forum.services.IMessageService;
import com.programming.forum.services.IUserService;
import com.programming.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 22479
 * Date: 2023-11-14
 * Time: 17:19
 */
@Service
@Slf4j
public class MessageServiceImpl implements IMessageService {

    @Resource
    private IUserService userService;
    @Resource
    private MessageMapper messageMapper;


    /**
     * 给新用户发送第一条站内信
     * @param newUserId
     */
    public void welComNewUser(Long newUserId) {
        Message message = new Message();
        message.setPostUserId(3L); // 管理员Id
        message.setReceiveUserId(newUserId); // 接收者Id
        message.setContent("欢迎新用户来到编程技术论坛！"); // 站内信的内容
        create(message);
    }

    /**
     * 创建一条站内信
     * @param message
     */
    @Override
    public void create(Message message) {
        //校验参数
        if(message == null || message.getPostUserId() == null || message.getReceiveUserId() == null ||
                StringUtil.isEmpty(message.getContent())) {
            //FAILED_PARAMS_VALIDATE  (1002, "参数校验失败"),
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验接收用户是否存在
        User user = userService.selectById(message.getReceiveUserId());
        if(user == null || user.getDeleteState() == 1) {
            //FAILED_PARAMS_VALIDATE  (1002, "参数校验失败"),
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //设置默认值
        message.setState((byte) 0);//0 未读
        message.setDeleteState((byte) 0);
        Date date = new Date();
        message.setCreateTime(date);
        message.setUpdateTime(date);
        //调用dao层方法
        int row = messageMapper.insertSelective(message);
        if(row != 1) {
            //  FAILED                  (1000, "操作失败"),
            log.warn(ResultCode.FAILED .toString() + "更新数据库异常");

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED ));
        }

    }


    @Override
    public Integer selectUnReadCount(Long receiveUserId) {
        //参数校验
        if(receiveUserId == null || receiveUserId <= 0) {
            //FAILED_PARAMS_VALIDATE  (1002, "参数校验失败"),
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用DAO
        Integer count = messageMapper.selectUnreadCount(receiveUserId);
        if(count == null || count < 0) {
            //  FAILED                  (1000, "操作失败"),
            log.warn(ResultCode.FAILED .toString() + "查询数据库异常");

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED ));
        }
        return count;
    }

    /**
     * 根据接受者用户Id查询所有站内信
     * @param receiveUserId
     * @return
     */
    @Override
    public List<Message> selectByReceiveUserId(Long receiveUserId) {
        //非空校验
        if(receiveUserId == null || receiveUserId < 0) {
            //FAILED_PARAMS_VALIDATE  (1002, "参数校验失败"),
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用DAO
        List<Message> messages = messageMapper.selectByReceiveUserId(receiveUserId);

        return messages;
    }

    /**
     * 根据站内信Id查询站内信
     * @param id
     * @return
     */
    @Override
    public Message selectById(Long id) {
        if(id == null || id < 0) {
            //FAILED_PARAMS_VALIDATE  (1002, "参数校验失败"),
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Message message = messageMapper.selectByPrimaryKey(id);
        return message;
    }

    /**
     * 更新指定站内信的状态
     * @param id 站内信Id
     * @param state 目标状态
     */
    @Override
    public void updateStateById(Long id, Byte state) {
        //非空校验 state 0 未读 1 已读 2已回复
        if(id == null || id < 0 || state < 0 || state > 2) {
            //FAILED_PARAMS_VALIDATE  (1002, "参数校验失败"),
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //构造更新对象
        Message updateMessage = new Message();
        updateMessage.setId(id);
        updateMessage.setState(state);
        Date data = new Date();
        updateMessage.setUpdateTime(data);
        int row = messageMapper.updateByPrimaryKeySelective(updateMessage);
        if(row != 1) {
            //  FAILED                  (1000, "操作失败"),
            log.warn(ResultCode.FAILED .toString() + "更新数据库异常");

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED ));
        }
    }


    @Override
    public void reply(Long repliedId, Message message) {
        //非空校验
        if(repliedId == null || repliedId < 0) {
            //FAILED_PARAMS_VALIDATE  (1002, "参数校验失败"),
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验站内信是否存在
        Message existsMessage = messageMapper.selectByPrimaryKey(repliedId);
        if(existsMessage == null || existsMessage.getDeleteState() == 1) {
            //FAILED_MESSAGE_NOT_EXISTS      (1401,"站内信不存在"),
            log.warn(ResultCode.FAILED_MESSAGE_NOT_EXISTS.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_MESSAGE_NOT_EXISTS));
        }

        //更新被回复的站内信的状态
        updateStateById(repliedId, (byte) 2);
        //回复的内容写入数据库
        create(message);
    }
}
